package com.example.qsindusty.jmm_spline.ReleaseOrder;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.example.qsindusty.jmm_spline.Config.Config;
import com.example.qsindusty.jmm_spline.OrdeFragment.OrderData;
import com.example.qsindusty.jmm_spline.R;
import com.example.qsindusty.jmm_spline.weight.ChoiceGoodsDialog;
import com.example.qsindusty.jmm_spline.weight.MyDialog;
import com.example.qsindusty.jmm_spline.weight.MyListview;
import com.google.gson.Gson;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.lljjcoder.Interface.OnCityItemClickListener;
import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.citywheel.CityConfig;
import com.lljjcoder.style.citylist.Toast.ToastUtils;
import com.lljjcoder.style.citypickerview.CityPickerView;
import com.yixin.ystartlibrary.base.BaseAppCompatActivity;
import com.yixin.ystartlibrary.utils.GeneralPreferencesUtils;
import com.yixin.ystartlibrary.utils.LoadingDialogUtils;
import com.yixin.ystartlibrary.utils.LogUtils;
import com.yixin.ystartlibrary.utils.StatusBarUtil;
import com.yixin.ystartlibrary.utils.Utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ReleaseOrderActivity extends BaseAppCompatActivity implements Contact.View,
        AdapterView.OnItemClickListener,
        OnDateSetListener,CallBackLister,CallBack2Lister,AdapterView.OnItemLongClickListener{
    CityPickerView mCityPickerView;
    @BindView(R.id.goodowner)
    TextInputEditText goodowner;
    @BindView(R.id.goodphone)
    TextInputEditText goodphone;
    @BindView(R.id.goodsaddress)
    TextView goodsaddress;
    @BindView(R.id.citypicker)
    Button citypicker;
    @BindView(R.id.getter)
    TextInputEditText getter;
    @BindView(R.id.getterphone)
    TextInputEditText getterphone;
    @BindView(R.id.geteraddress)
    TextView geteraddress;
    @BindView(R.id.gettercitypicker)
    Button gettercitypicker;
    @BindView(R.id.goodstime)
    TextView goodstime;
    @BindView(R.id.timepicker)
    Button timepicker;
    @BindView(R.id.loadingdata)
    Button loadingdata;
    @BindView(R.id.adddata)
    Button adddata;
    @BindView(R.id.mylistview)
    MyListview mylistview;
    @BindView(R.id.goodsdetailaddress)
    TextInputEditText goodsdetailaddress;
    @BindView(R.id.getterdetailaddress)
    TextInputEditText getterdetailaddress;
    TimePickerDialog mDialogAll ;
    MyDialog myDialog ;
    ChoiceGoodsDialog choiceGoodsDialog ;
    String datastr ;
    MyAdapter orderAdapter ;
    ArrayList<GoodData.DataBean> yourChoices = new ArrayList<>();
    ReleasePresenter mPresemnter ;
    OrderData.DataBean dataBean ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_release_order);
        ButterKnife.bind(this);
        StatusBarUtil.immersive(this.getWindow());
        StatusBarUtil.setPaddingSmart(this, mToolBar);

    }


    @Override
    protected void init() {
        setCenterTitle("创建子订单");
        setEnabledNavigation(true);
        orderAdapter= new MyAdapter(yourChoices,mActivity);
        mylistview.setAdapter(orderAdapter);
        mylistview.setOnItemClickListener(this);
        mCityPickerView = new CityPickerView();
        mCityPickerView.init(this);
        datastr = GeneralPreferencesUtils.getSharedPreference(mActivity, Config.userinfo,null);
        intiview();
        bindPresenter();
        mylistview.setOnItemLongClickListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
            unbindPresenter();
    }

    private  void  intiview( ){
        dataBean= (OrderData.DataBean) getIntent().getSerializableExtra(Config.data);
        if (!TextUtils.isEmpty(dataBean.getFJR()))
            goodowner.setText(dataBean.getFJR());
        if (!TextUtils.isEmpty(dataBean.getFJRDH()))
            goodphone.setText(dataBean.getFJRDH());
        if (!TextUtils.isEmpty(dataBean.getFJRDZ()))
            goodsaddress.setText(dataBean.getFJRDZ());
        if (!TextUtils.isEmpty(dataBean.getFJRDZ()))
            goodsdetailaddress.setText(dataBean.getFJRDZ());
        if (!TextUtils.isEmpty(dataBean.getSJR()))
            getter.setText(dataBean.getFJR());
        if (!TextUtils.isEmpty(dataBean.getSJRDH()))
            getterphone.setText(dataBean.getSJRDH());
        if (!TextUtils.isEmpty(dataBean.getSJRDZ()))
            geteraddress.setText(dataBean.getSJRDZ());
        if (!TextUtils.isEmpty(dataBean.getSJRDZ()))
            getterdetailaddress.setText(dataBean.getSJRDZ());
        if (!TextUtils.isEmpty(dataBean.getFHSJ()))
            goodstime.setText(dataBean.getFHSJ());
        yourChoices.clear();
        for (OrderData.DataBean.GOODSLISTBean goodslistBean:dataBean.getGOODSLIST()){
            GoodData.DataBean gooddata= new GoodData.DataBean();
            gooddata.setMC(goodslistBean.getMC());
            gooddata.setSL(goodslistBean.getSL());
            gooddata.setDW(goodslistBean.getDW());
            gooddata.setBZ(goodslistBean.getBZ());
            yourChoices.add(gooddata);
        }
                orderAdapter.notifyDataSetChanged();

    }




    /**
     * 城市选择器
     * @param status
     */
    private void wheel(final String status) {
        String defaultProvinceName = "重庆市";
        String defaultCityName = "重庆市";
        String defaultDistrict = "渝北区";
        int visibleItems = 5;
        CityConfig cityConfig = new CityConfig.Builder()
                .title("选择城市")//标题
                .province(defaultProvinceName)
                .city(defaultCityName)
                .district(defaultDistrict)
                .districtCyclic(true)
                .provinceCyclic(true)
                .cityCyclic(true)
                .titleBackgroundColor("#428685")
                .visibleItemsCount(visibleItems)
                .confirTextColor("#ffffffff")
                .cancelTextColor("#ffffffff")
                .titleTextColor("#ffffffff")
                .build();
        mCityPickerView.setConfig(cityConfig);
        mCityPickerView.setOnCityItemClickListener(new OnCityItemClickListener() {
            @Override
            public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {
                StringBuilder sb = new StringBuilder();
                if (province != null) {
                    sb.append(province.getName());
                }
                if (city != null) {
                    sb.append(city.getName());
                }
                if (district != null) {
                    sb.append(district.getName());
                }
            if (TextUtils.equals(status,"0"))
                goodsaddress.setText("" + sb.toString());
            if (TextUtils.equals(status,"1"))
                geteraddress.setText("" + sb.toString());

            }

            @Override
            public void onCancel() {
                ToastUtils.showLongToast(mActivity, "已取消");
            }
        });
        mCityPickerView.showCityPicker();
    }

    /**
     * 时间选择器
     */
    private  void  setTimepickdialog(){
        long tenYears = 10L * 365 * 1000 * 60 * 60 * 24L;
        mDialogAll = new TimePickerDialog.Builder()
                .setCallBack(this)
                .setCancelStringId("取消")
                .setSureStringId("确定")
                .setTitleStringId("选择时间")
                .setYearText("年")
                .setMonthText("月")
                .setDayText("日")
                .setHourText("时")
                .setMinuteText("分")
                .setCyclic(true)
                .setMinMillseconds(System.currentTimeMillis())
                .setMaxMillseconds(System.currentTimeMillis() + tenYears)
                .setCurrentMillseconds(System.currentTimeMillis())
                .setThemeColor(getResources().getColor(R.color.theme_color))
                .setType(Type.ALL)
                .setWheelItemTextNormalColor(getResources().getColor(R.color.timetimepicker_default_text_color))
                .setWheelItemTextSelectorColor(getResources().getColor(R.color.black))
                .setWheelItemTextSize(12)
                .build();
        mDialogAll.show(getSupportFragmentManager(), "all");
    }
    private  void  setaddDialog(){
            myDialog = new MyDialog.Builder()
                    .setCallback(this)
                    .setflag(0)
                    .setBackgounrd(R.color.lighter_gray)
                    .setTitleColor(R.color.black)
                    .setTitle("请添加货物信息")
                    .setSuretext("添加")
                    .setCanceltext("取消")
                    .setButttonColor(R.color.theme_color)
                    .setcancelButttonColor(R.color.white)
                    .setsureButttonColor(R.color.white)
                    .build();
            myDialog.show(getSupportFragmentManager(),"y");
    }
    private  void  setaddDialog(GoodData.DataBean goodslistBean,int position){
            myDialog = new MyDialog.Builder()
                    .setCallback(this)
                    .setflag(1)
                    .setposition(position)
                    .setBackgounrd(R.color.lighter_gray)
                    .setTitleColor(R.color.black)
                    .setTitle("请添加货物信息")
                    .setSuretext("添加")
                    .setGooddata(goodslistBean)
                    .setCanceltext("取消")
                    .setButttonColor(R.color.theme_color)
                    .setcancelButttonColor(R.color.white)
                    .setsureButttonColor(R.color.white)
                    .build();
            myDialog.show(getSupportFragmentManager(),"y");
    }
    private void  setMulitChoiceDialog(){
        choiceGoodsDialog = new ChoiceGoodsDialog.Builder()
                .setBackgounrd(R.color.white)
                .setSuretext("确定")
                .setCanceltext("取消")
                .setCallback(this)
                .build();
        choiceGoodsDialog.show(getSupportFragmentManager(),"y");
}


    @OnClick({R.id.citypicker, R.id.gettercitypicker, R.id.timepicker, R.id.loadingdata, R.id.adddata})
    public void onViewClicked(View view) {
            //0 为发货 1为接货
        switch (view.getId()) {
            case R.id.citypicker:
                wheel("0");
                break;
            case R.id.gettercitypicker:
                wheel("1");
                break;
            case R.id.timepicker:
                setTimepickdialog();
                break;
            case R.id.loadingdata:
              setMulitChoiceDialog();
                break;
            case R.id.adddata:
                setaddDialog();
                break;
        }
    }

    @Override
    public void onDateSet(TimePickerDialog timePickerDialog, long millseconds) {
        String text = getDateToString(millseconds);
        goodstime.setText(text);
    }

    public String getDateToString(long time) {
        Date d = new Date(time);
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sf.format(d);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (TextUtils.isEmpty(goodowner.getText().toString().trim())){
            ToastUtils.showLongToast(mActivity,"请添加发件人");
            return false ;
        }
        if (TextUtils.isEmpty(goodphone.getText().toString().trim())){
            ToastUtils.showLongToast(mActivity,"请添加发件人电话");
            return false ;
        }
        if (TextUtils.isEmpty(goodsaddress.getText().toString().trim())){
            ToastUtils.showLongToast(mActivity,"请添加发件人地址");
            return false ;
        }
        if (TextUtils.isEmpty(goodsdetailaddress.getText().toString().trim())){
            ToastUtils.showLongToast(mActivity,"请添加发件人详细地址");
            return false ;
        }
        if (TextUtils.isEmpty(getter.getText().toString().trim())){
            ToastUtils.showLongToast(mActivity,"请添加收件人");
            return false ;
        }
        if (TextUtils.isEmpty(getterphone.getText().toString().trim())){
            ToastUtils.showLongToast(mActivity,"请添加发件人电话");
            return false ;
        }
        if (TextUtils.isEmpty(geteraddress.getText().toString().trim())){
            ToastUtils.showLongToast(mActivity,"请添加发件人地址");
            return false ;
        }
        if (TextUtils.isEmpty(getterdetailaddress.getText().toString().trim())){
            ToastUtils.showLongToast(mActivity,"请添加发件人详细地址");
            return false ;
        }
        if (TextUtils.isEmpty(goodstime.getText().toString().trim())){
            ToastUtils.showLongToast(mActivity,"请添加发货时间");
            return false ;
        }

            if (orderAdapter.getCount()==0){
                ToastUtils.showLongToast(mActivity,"请添加货品");
                return false ;
            }

            ReleaseData releaseData = new ReleaseData();
            releaseData.setFJR(goodowner.getText().toString().trim());
            releaseData.setFJRDH(goodphone.getText().toString().trim());
            StringBuffer sb = new StringBuffer();
            sb.append(goodsaddress.getText().toString().trim())
                    .append(goodsdetailaddress.getText().toString().trim());
            releaseData.setFJRDZ(goodsdetailaddress.getText().toString().trim());
            releaseData.setSJR(getter.getText().toString().trim());
            releaseData.setSJRDH(getterphone.getText().toString().trim());
            StringBuffer sb1 = new StringBuffer();
            sb1.append(geteraddress.getText().toString().trim())
                .append(getterdetailaddress.getText().toString().trim());
            releaseData.setSJRDZ(getterdetailaddress.getText().toString().trim());
            releaseData.setFHSJ(goodstime.getText().toString().trim());
            List<ReleaseData.GOODSLISTBean> list = new ArrayList<>();

            for (GoodData.DataBean dataBean :orderAdapter.getAllInfoList()){
                ReleaseData.GOODSLISTBean goodslistBean = new ReleaseData.GOODSLISTBean();
                if (!TextUtils.isEmpty(dataBean.getBZ()))
                goodslistBean.setBZ(dataBean.getBZ());
                goodslistBean.setMC(dataBean.getMC());
                goodslistBean.setDW(dataBean.getDW());
                goodslistBean.setSL(dataBean.getSL());
                    list.add(goodslistBean);
            }
            releaseData.setGOODSLIST(list);
            releaseData.setSJLY(Config.android);
        Gson gson = new Gson();
     String jsondata =   gson.toJson(releaseData);
        LogUtils.i(jsondata);
        String token = GeneralPreferencesUtils.getSharedPreference(mActivity,Config.token,null);
                mPresemnter.creatChildOrder(token,dataBean.getXH(),dataBean.getQYXH(),jsondata);

        return false;
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.mark_location, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
            menu.findItem(R.id.mark_location).setTitle("创建子订单");
        return super.onPrepareOptionsMenu(menu);
    }

    /**
     * 新增回调
     * @param flag
     * @param goodData
     */
    @Override
    public void callback(int flag,GoodData.DataBean goodData) {
            if (flag==0){
            yourChoices.add(0,goodData);
            orderAdapter.notifyDataSetChanged();
            }


    }

    /**
     * 修改回调
     * @param flag
     * @param goodData
     * @param position
     */
    @Override
    public void callback(int flag, GoodData.DataBean goodData, int position) {
        yourChoices.remove(position);
        yourChoices.add(position,goodData);
        orderAdapter.notifyDataSetChanged();
    }

    /**
     * 多选回调
     * @param flag
     * @param dataBeans
     */
    @Override
    public void callback(int flag, List<GoodData.DataBean> dataBeans) {
        if (flag==0){
            for (GoodData.DataBean dataBean:dataBeans){
                yourChoices.add(0,dataBean);
            }
            orderAdapter.notifyDataSetChanged();
        }
    }

    AlertDialog alertDialog;

    @Override
    public void showLoading() {
        alertDialog = LoadingDialogUtils.create(mActivity, "");
        alertDialog.show();

    }

    @Override
    public void closeLoading() {
        if (alertDialog != null && alertDialog.isShowing())
            alertDialog.dismiss();
    }

    /**
     * 绑定presenter
     */
    @Override
    public void bindPresenter() {
        if (mPresemnter == null) {
            mPresemnter = new ReleasePresenter();
        }
        mPresemnter.bindView(this);
    }

    /**
     * 解除绑定presenter
     */
    @Override
    public void unbindPresenter() {
        mPresemnter.unbindView();
    }

    @Override
    public void Successful(String msg) {
        ToastUtils.showLongToast(mActivity,msg);
        //    ReleasedFragment.isFresh=true;
        finish();
    }

    @Override
    public void Frailer(String msg) {
        ToastUtils.showLongToast(mActivity,msg);
    }


    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        GoodData.DataBean   dataBean=orderAdapter.getitemInfo(i);
        setaddDialog(dataBean,i);
    }
    private void dialogList(final int postion) {
        final String items[] = { "删除"};
        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);

        // builder.setMessage("是否确认退出?"); //设置内容
        // 设置列表显示，注意设置了列表显示就不要设置builder.setMessage()了，否则列表不起作用。
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                ToastUtils.showLongToast(mActivity,"删除");
                yourChoices.remove(postion);
                orderAdapter.notifyDataSetChanged();
            }
        });
        builder.create().show();
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                dialogList(i);

        return true;
    }


    public class MyAdapter extends BaseAdapter {

        private List<GoodData.DataBean> list = null;

        private Context context = null;

        private LayoutInflater inflater = null;

        public MyAdapter(List<GoodData.DataBean> list, Context context) {
            this.list = list;
            this.context = context;
            // 布局装载器对象
            inflater = LayoutInflater.from(context);
        }

        // 适配器中数据集中数据的个数
        @Override
        public int getCount() {
            return list.size();
        }

        // 获取数据集中与指定索引对应的数据项
        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        // 获取指定行对应的ID
        @Override
        public long getItemId(int position) {
            return position;
        }
        public List<GoodData.DataBean> getAllInfoList() {
            return list;
        }
        public  GoodData.DataBean getitemInfo(int position){
            return list.get(position);
        }

        // 获取每一个Item显示的内容


        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            GoodData.DataBean itemBean = list.get(position);
            View view = inflater.inflate(R.layout.item_choice, null);
            TextView title = (TextView) view.findViewById(R.id.goods);
            StringBuffer sb = new StringBuffer();
                sb.append("货品："+itemBean.getMC()).append("  ")
                  .append("数量："+itemBean.getSL()).append("  ")
                  .append("单位："+itemBean.getDW()).append("   ");
                 if (!TextUtils.isEmpty(itemBean.getBZ()))
                    sb.append("备注："+itemBean.getBZ());
                     title.setText(sb.toString());

            return view;
        }
    }

}
